from playwright.sync_api import sync_playwright
import time
import os

def run_novel_login():
    print("开始运行小说网站登录示例...")
    with sync_playwright() as p:
        # 启动Chromium浏览器（非无头模式，方便观察）
        browser = p.chromium.launch(
            headless=False,
            slow_mo=100  # 每个操作之间延迟100毫秒
        )
        page = browser.new_page()
        
        try:
            # 访问小说网站登录页面
            print("正在访问小说网站登录页面...")
            page.goto("http://novel.hctestedu.com/user/login.html", timeout=60000)
            
            # 等待页面加载完成
            page.wait_for_load_state("load")
            print("登录页面加载完成")
            
            # 等待一下，确保页面完全渲染
            time.sleep(2)
            
            # 定位用户名输入框并填入账号
            print("正在填入账号...")
            page.wait_for_selector("#username", state="visible", timeout=20000)
            username_input = page.locator("#username")
            username_input.fill("18511112222")
            print("账号填入完成")
            
            # 定位密码输入框并填入密码
            print("正在填入密码...")
            page.wait_for_selector("#password", state="visible", timeout=10000)
            password_input = page.locator("#password")
            password_input.fill("123456")
            print("密码填入完成")
            
            # 定位登录按钮并点击
            print("正在点击登录按钮...")
            page.wait_for_selector(".login_btn .btn", state="visible", timeout=10000)
            login_button = page.locator(".login_btn .btn")
            login_button.click()
            print("已点击登录按钮")
            
            # 等待登录结果
            page.wait_for_load_state("networkidle")
            print("登录请求已完成")
            
            # 等待几秒，让用户可以看到结果
            time.sleep(5)
            
            # 截图保存 - 使用绝对路径
            screenshot_path = os.path.join(os.getcwd(), "novel_login_result.png")
            page.screenshot(path=screenshot_path)
            print(f"已保存截图到: {screenshot_path}")
            
        except Exception as e:
            print(f"发生错误: {e}")
            # 保存错误状态截图用于调试
            error_screenshot_path = os.path.join(os.getcwd(), "novel_login_error.png")
            page.screenshot(path=error_screenshot_path)
            print(f"已保存错误状态截图到: {error_screenshot_path}")
        finally:
            # 等待用户确认后再关闭浏览器
            input("按Enter键关闭浏览器...")
            browser.close()
            print("浏览器已关闭")

if __name__ == "__main__":
    run_novel_login()